<?php
namespace app\admin\controller;

use app\common\controller\AdminBase;
use think\Config;
use think\Db;
use think\Log;

class AdminUser extends AdminBase
{
    private $admin_user_model;
    private $admin_user_group_model;
    private $auth_group_model;
    private $auth_group_access_model;

    public function _initialize()
    {
        parent::_initialize();
        $this->admin_user_model = model('AdminUser');
        $this->admin_user_group_model = model('AdminUserGroup');
        $this->auth_group_model = model('AuthGroup');
        $this->auth_group_access_model = model('AuthGroupAccess');

    }


    /**
     * 人员列表
     * @return mixed
     */
    public function index()
    {
        $username = $this->request->param('username', '', 'trim');
        $where = [];
        if (!empty($username)) {
            $where['username'] = $username;
        }

        $admin_user_list = $this->admin_user_model->getList($where, $this->pageLimit);

        $user_group_arr = [];
        foreach ($admin_user_list as $v) {
            //获取每个人员的分组
            $group_list = $this->admin_user_group_model->getList([
                'id' => $v->id,
            ], 10, false, 'title');
            if (empty($group_list['data'])) {
                $user_group_arr[$v->id] = '';
            } else {
                $user_group_arr[$v->id] = implode(',', array_column($group_list['data'], 'title'));
            }
        }

        return $this->fetch('index', [
            'admin_user_list' => $admin_user_list,
            'username' => $username,
            'user_group_arr' => $user_group_arr,
            'user_id' => $this->userInfo['id'],
        ]);
    }


    /**
     * 添加人员
     * @return mixed
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            Db::startTrans();
            $data            = $this->request->post();

            //数据验证
            if (empty($data['username'])) {
                return ajax_return_error('登录名不能为空！');
            }

            if (empty($data['password']) || empty($data['confirm_password'])) {
                return ajax_return_error('密码不能为空！');
            }

            if ($data['password'] !== $data['confirm_password']) {
                return ajax_return_error('两次密码不一致！');
            }

            if (!empty($data['email']) && !is_email($data['email'])) {
                return ajax_return_error('请输入正确的邮箱地址！');
            }

            //检查人员是否存在
            $check_exist = $this->admin_user_model->getInfo(['username' => $data['username']], 'username', true);
            if ($check_exist) {
                return ajax_return_error('人员已经存在,请勿重复添加！');
            }

            //获取用户的角色id
            $group_ids = $data['group_id'];
            $group_ids = array_unique(array_filter(array_map(function ($v){
                return (int)$v;
            }, $group_ids)));
            if (empty($group_ids)) {
                return ajax_return_error('请未人员指定角色！');
            }

            $user_data = [
                'username'  => $data['username'],
                'password'  => md5($data['password'] . Config::get('salt')),
                'status'    => 1,
                'email'     => $data['email'],
            ];
            $add_user_id = $this->admin_user_model->addData($user_data);
            if ($add_user_id) {
                //插入角色
                foreach ($group_ids as $v) {
                    $res = $this->auth_group_access_model->addData([
                        'uid'       => $add_user_id,
                        'group_id'  => $v,
                    ]);
                    if (!$res) {
                        Db::rollback();
                        return ajax_return_error('保存失败');
                    }
                }

                Db::commit();
                return ajax_return_adv('保存成功');
            } else {
                Db::rollback();
                return ajax_return_error('保存失败');
            }

        }

        $auth_group_list = $this->auth_group_model->getAllGroup();
        return $this->fetch('add', [
            'auth_group_list' => $auth_group_list,
        ]);
    }


    /**
     * 编辑人员
     * @return mixed
     */
    public function edit()
    {
        $id = $this->request->param('id', 0, 'intval');
        $data            = $this->request->post();

        $user_info = $this->admin_user_model->getInfo([
            'id' => $id,
        ]);

        //获取用户之前所在的角色
        $group_list = $this->admin_user_group_model->getList([
            'id' => $id,
        ], 10, false, 'group_id');
        $group_list = array_column($group_list['data'], 'group_id');
        $old_group_count = count($group_list);
        $group_list = array_unique(array_filter(array_map(function ($v){
            return (int)$v;
        }, $group_list)));

        if ($this->request->isAjax() && $id > 0) {
            //数据验证
            if (empty($data['username'])) {
                return ajax_return_error('登录名不能为空！');
            }

            if (!empty($data['email']) && !is_email($data['email'])) {
                return ajax_return_error('请输入正确的邮箱地址！');
            }

            //检查人员是否存在
            if ($data['username'] != $user_info->username &&
                $this->admin_user_model->getInfo(['username' => $data['username']], 'username', true)
            ) {
                return ajax_return_error('人员已经存在,请勿重复添加！');
            }

            $user_data = [
                'username'  => $data['username'],
                'email'     => $data['email'],
            ];
            $edit_res = $this->admin_user_model->saveDate($id, $user_data);
            if ($edit_res !== false) {
                //获取用户最新的角色id
                $group_ids = $data['group_id'];
                $group_ids = array_unique(array_filter(array_map(function ($v){
                    return (int)$v;
                }, $group_ids)));
                if (empty($group_ids)) {
                    return ajax_return_error('请未人员指定角色！');
                }

                //检查人员的角色信息是否发生变化
                if (array_diff($group_list, $group_ids) || array_diff($group_ids, $group_list)) {
                    //删除所有原来的角色
                    $del_res = $this->auth_group_access_model->delData([
                        'uid' => $id,
                    ]);
                    if ($del_res === false || $del_res > $old_group_count) {
                        Db::rollback();
                        return ajax_return_error('保存失败');
                    }
                    //重新增加此次分配的角色
                    foreach ($group_ids as $v) {
                        $res = $this->auth_group_access_model->addData([
                            'uid'       => $id,
                            'group_id'  => $v,
                        ]);
                        if (!$res) {
                            Db::rollback();
                            return ajax_return_error('保存失败');
                        }
                    }
                }

                Db::commit();
                return ajax_return_adv('保存成功');
            } else {
                Db::rollback();
                return ajax_return_error('保存失败');
            }
        }

        $auth_group_list = $this->auth_group_model->getAllGroup();

        return $this->fetch('edit', [
            'auth_group_list' => $auth_group_list,
            'user_info' => $user_info,
            'group_list' => $group_list,
            'cannot_edit' => ($this->userInfo['id'] != 1 && $id == 1)  ? true : false,
        ]);
    }

    /**
     * 修改人员的账号的状态
     */
    public function change_user_status()
    {
        if ($this->request->isAjax()) {
            $user_id = $this->request->param('user_id', 0, 'intval');
            if ($user_id <= 0) {
                return ajax_return_error('参数错误（未指定人员）');
            }
            $status = $this->request->param('status', 1, 'intval');
            if ($status != 0 && $status != 1) {
                $status = 1;
            }

            if ($user_id == 1) {
                return ajax_return_error('超级管理员不能被禁用');
            }

            $res = $this->admin_user_model->saveDate($user_id, [
                'status' => $status,
            ]);
            if ($res === false) {
                return ajax_return_error('操作失败');
            }

            return ajax_return_adv('操作成功');
        }
    }

    /**
     * 修改密码
     */
    public function change_passwd()
    {
        $user_id = $this->request->param('user_id', 0, 'intval');
        if ($this->request->isAjax()) {
            if ($this->userInfo['id'] != $user_id) {
                //检查人员是否存在
                $user_info = $this->admin_user_model->getInfo(['id' => $user_id], 'id');
                if (empty($user_info)) {
                    return ajax_return_error('人员不存在，或已被删除了！');
                }
            }

            $password = $this->request->param('password', '', 'trim');
            $confirm_password = $this->request->param('confirm_password', '', 'trim');
            if (!empty($password)) {
                if ($password !== $confirm_password) {
                    return ajax_return_error('两次密码不一致！');
                }

                //只有超级管理员才可以修改别人的密码
                if (($this->userInfo['id'] != 1 || !in_array(1, $this->userInfo['group_id'])) && $this->userInfo['id'] != $user_id) {
                    return ajax_return_error('抱歉，只有超级管理员才可以修改他人的密码哦！');
                }

                $edit_data = [
                    'password'  => md5($password . Config::get('salt')),
                ];
                $edit_res = $this->admin_user_model->saveDate($user_id, $edit_data);
                if ($edit_res === false) {
                    return ajax_return_error('修改失败！');
                } else {
                    return ajax_return_adv('修改成功！');
                }
            } else {
                //不进行任何操作
                return ajax_return_adv('未进行任何修改！');
            }
        }
        return $this->fetch('chpwd', ['user_id' => $user_id]);
    }


    /**
     * 删除人员 （可批量）
     */
    public function delete()
    {
        $ids = $this->request->param('ids', '', 'trim');
        $ids = explode(',', $ids);
        $ids = array_unique(array_filter(array_map(function($v){
            return (int)$v;
        }, $ids)));

        if ($this->request->isAjax()) {
            if (empty($ids)) {
                return ajax_return_adv('未进行任何删除！');
            }

            if (in_array(1, $ids)) {
                return ajax_return_error('超级账号不能被删除！');
            }

            if (!$this->admin_user_model->destroy($ids)) {
                return ajax_return_error('删除失败！');
            }

            return ajax_return_adv('删除成功！');
        }
    }

    /**
     * 查看自己的个人信息
     */
    public function info()
    {
        //全部分组
        $auth_group_list = $this->auth_group_model->getAllGroup();
        return $this->fetch('info', [
            'user_info' => $this->userInfo,
            'auth_group_list' => $auth_group_list,
        ]);
    }

    /**
     * 修改密码（只能修改自己的）
     */
    public function edit_passwd()
    {
        if ($this->request->isAjax()) {
            $password = $this->request->param('password', '', 'trim');
            $confirm_password = $this->request->param('confirm_password', '', 'trim');
            if ($password !== $confirm_password) {
                return ajax_return_error('两次密码不一致！');
            }

            $edit_data = [
                'password'  => md5($password . Config::get('salt')),
            ];
            $edit_res = $this->admin_user_model->saveDate($this->userInfo['id'], $edit_data);
            if ($edit_res === false) {
                return ajax_return_error('修改失败！');
            } else {
                return ajax_return_adv('修改成功！');
            }
        }

        return $this->fetch();
    }
}
